﻿/* Copyright (c) 2010 EPiServer AB
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using EPiServer.Core;
using EPiServer.Filters;
using EPiServer.Municipality.Configuration;
using EPiServer.Web.WebControls;

namespace EPiServer.Municipality.Web.UI.WebControls {
    /// <summary>
    /// Summary description for IndexList.
    /// </summary>
    /// <remarks></remarks>
    /// <example></example>
    public class IndexList : CompositeDataBoundControl {
        /* *******************************************************************
        *  Properties 
        * *******************************************************************/
        #region public ITemplate ItemTemplate
        /// <summary>
        /// Get/Sets the ItemTemplate of the IndexList
        /// </summary>
        /// <value></value>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(PageTemplateContainer))]
        public ITemplate ItemTemplate {
            get {
                return _itemTemplate;
            }
            set {
                _itemTemplate = value;
            }
        }
        private ITemplate _itemTemplate;
        #endregion
        #region public ITemplate ExternalLinkItemTemplate
        /// <summary>
        /// Get/Sets the ExternalLinkItemTemplate of the IndexList
        /// </summary>
        /// <value></value>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(PageTemplateContainer))]
        public ITemplate ExternalLinkItemTemplate {
            get {
                return _externalLinkItemTemplate;
            }
            set {
                _externalLinkItemTemplate = value;
            }
        }
        private ITemplate _externalLinkItemTemplate;
        #endregion
        #region public ITemplate LastInGroupItemTemplate
        /// <summary>
        /// Get/Sets the LastInGroupItemTemplate of the IndexList
        /// </summary>
        /// <value></value>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(PageTemplateContainer))]
        public ITemplate LastInGroupItemTemplate {
            get {
                return _lastInGroupItemTemplate;
            }
            set {
                _lastInGroupItemTemplate = value;
            }
        }
        private ITemplate _lastInGroupItemTemplate;
        #endregion
        #region public ITemplate PrefixTemplate
        /// <summary>
        /// Get/Sets the PrefixTemplate of the IndexList
        /// </summary>
        /// <value></value>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(PageTemplateContainer))]
        public ITemplate PrefixTemplate {
            get {
                return _prefixTemplate;
            }
            set {
                _prefixTemplate = value;
            }
        }
        private ITemplate _prefixTemplate;
        #endregion
        #region public ITemplate HeaderTemplate
        /// <summary>
        /// Get/Sets the HeaderTemplate of the AlphaNumericList
        /// </summary>
        /// <value></value>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(PageTemplateContainer))]
        public ITemplate HeaderTemplate {
            get {
                return _headerTemplate;
            }
            set {
                _headerTemplate = value;
            }
        }
        private ITemplate _headerTemplate;
        #endregion
        #region public ITemplate FooterTemplate
        /// <summary>
        /// Get/Sets the FooterTemplate of the AlphaNumericList
        /// </summary>
        /// <value></value>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(PageTemplateContainer))]
        public ITemplate FooterTemplate {
            get {
                return _footerTemplate;
            }
            set {
                _footerTemplate = value;
            }
        }
        private ITemplate _footerTemplate;
        #endregion
        /* *******************************************************************
        *  Constructors 
        * *******************************************************************/
        /* *******************************************************************
        *  Methods 
        * *******************************************************************/
        /* *******************************************************************
        *  Event methods 
        * *******************************************************************/
        #region protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataSource"></param>
        /// <param name="dataBinding"></param>
        /// <returns></returns>
        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding) {

            if (dataBinding) {

                IEnumerator e = dataSource.GetEnumerator();
                var pages = new PageDataCollection();

                while (e.MoveNext()) {
                    var page = new PageTemplateContainer(e.Current as PageData);
                    pages.Add(page.CurrentPage);
                    if (page.CurrentPage[Constants.SYNONYM] != null) {
                        string[] synonym = ((string)page.CurrentPage[Constants.SYNONYM]).Split(',');
                        foreach (string alias in synonym) {
                            string str = alias;
                            if (str[0] == ' ')
                                str = str.Remove(0, 1);
                            var addPage = new PageData(PageReference.EmptyReference);
                            addPage.Property["PageName"] = new PropertyString(str);
                            addPage.Property["PageLinkURL"] = new PropertyString(page.CurrentPage.LinkURL);
                            addPage.Property["PageShortcutType"] = new PropertyNumber((int)page.CurrentPage.LinkType);
                            addPage.Property["PagePendingPublish"] = new PropertyBoolean(false);
                            pages.Add(addPage);
                        }
                    }
                }

                if (pages.Count == 0)
                    return 0;

                var sort = new FilterSort(FilterSortOrder.Alphabetical);
                sort.Sort(pages);

                for (int i = 0; i < pages.Count; i++) {

                    Control template = new PageTemplateContainer(pages[i]);

                    if (_headerTemplate != null) {
                        _headerTemplate.InstantiateIn(template);
                        template.DataBind();
                        Controls.Add(template);
                    }

                    if (_prefixTemplate != null) {
                        if (i == 0 || pages[i].PageName.Substring(0, 1).ToLower() != pages[i - 1].PageName.Substring(0, 1).ToLower()) {
                            _prefixTemplate.InstantiateIn(template);
                            template.DataBind();
                            Controls.Add(template);
                        }
                    }

                    if (_externalLinkItemTemplate != null) {
                        if (pages[i].LinkType == PageShortcutType.External) {
                            _externalLinkItemTemplate.InstantiateIn(template);
                            template.DataBind();
                            Controls.Add(template);
                        } else {
                            _itemTemplate.InstantiateIn(template);
                            template.DataBind();
                            Controls.Add(template);
                        }
                    }

                    if (_lastInGroupItemTemplate != null) {
                        if (i + 1 == pages.Count || pages[i].PageName.Substring(0, 1).ToLower() != pages[i + 1].PageName.Substring(0, 1).ToLower()) {
                            _lastInGroupItemTemplate.InstantiateIn(template);
                            template.DataBind();
                            Controls.Add(template);
                        }
                    }

                    if (_footerTemplate != null) {
                        _footerTemplate.InstantiateIn(template);
                        template.DataBind();
                        Controls.Add(template);
                    }
                }
                return pages.Count;
            }
            return 0;
        }
        #endregion
        #region public override void RenderBeginTag(HtmlTextWriter writer)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        public override void RenderBeginTag(HtmlTextWriter writer) {
        }
        #endregion
        #region public override void RenderEndTag(HtmlTextWriter writer)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        public override void RenderEndTag(HtmlTextWriter writer) {
        }
        #endregion
    }
}